package com.fht.controller.promotion;


import com.fht.entity.*;
import com.fht.enums.ManagermentSystemEnum;
import com.fht.exception.ManagermentSystemException;
import com.fht.from.promotionFrom;
import com.fht.service.food.FoodCategoryService;
import com.fht.service.food.MerchantsInformationService;
import com.fht.service.member.MemberCategoryService;
import com.fht.service.promotion.PromotionCategoryService;
import com.fht.service.promotion.PromotionSpecialOfferParticularsService;
import com.fht.service.promotion.PromotionSpecialOfferService;
import com.fht.util.GenerateOrdersIDUtil;
import com.fht.util.ResultVOUtil;
import com.fht.vo.LayUITableVO;
import com.fht.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.lang.reflect.InvocationTargetException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.fht.constant.ManagermentSystemConstant.PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP;

@Controller
@Slf4j
@RequestMapping("/promotion/specialOffer")
public class PromotionSpecialOfferController {


    @Autowired
    public PromotionSpecialOfferService promotionSpecialOfferService;

    @Autowired
    public PromotionSpecialOfferParticularsService promotionSpecialOfferParticularsService;

    @Autowired
    public MemberCategoryService memberCategoryService;

    @Autowired
    public FoodCategoryService foodCategoryService;

    @Autowired
    public PromotionCategoryService promotionCategoryService;


    @Autowired
    public MerchantsInformationService merchantsInformationService;


    //菜品类别展示
    @GetMapping("/index")
    public String index(Model model){

        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        model.addAttribute("merchantsInformationList",merchantsInformationList);

        return "promotion/specialOffer/index";

    }

    //获取菜品类别信息
    @GetMapping("/list")
    @ResponseBody
    public LayUITableVO<List<PromotionSpecialOffer>> list (@RequestParam(defaultValue = "1") Integer page,
                                                           @RequestParam(defaultValue = "10") Integer limit,
                                                           promotionFrom from){
        Map<String ,Object> map = new HashMap<>();
        map.put("page",page);
        map.put("limit",limit);
        map.put("from",from);

        LayUITableVO<List<PromotionSpecialOffer>> vo = promotionSpecialOfferService.findPage(map);


        return vo;
    }

    //修改map缓存中的数据，并重新计算价格总和
    @PostMapping("/editStatus")
    @ResponseBody
    public ResultVO editMap (PromotionSpecialOffer promotionSpecialOffer){


        promotionSpecialOfferService.update(promotionSpecialOffer);


        return ResultVOUtil.ok();
    }

    //跳转到修改页面
    @GetMapping("/edit-ui")
    public String editUI(String id,Model model){

       PromotionSpecialOffer promotionSpecialOffer = promotionSpecialOfferService.selectById(id);
        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        List<MemberCategory> memberCategoryList = memberCategoryService.selectAll();

        List<PromotionCategory> promotionCategoryList = promotionCategoryService.selectAll();

        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("promotionSpecialOffer",promotionSpecialOffer);
        model.addAttribute("memberCategoryList",memberCategoryList);
        model.addAttribute("promotionCategoryList",promotionCategoryList);

        return "promotion/specialOffer/edit";

    }

    //查询订单详情信息，并放入map缓存中
    @GetMapping("/recordList")
    @ResponseBody
    public LayUITableVO<List<PromotionSpecialOfferParticulars>> ordersList (@RequestParam(defaultValue = "1") Integer page,
                                                                     @RequestParam(defaultValue = "10") Integer limit,
                                                                     String id){

        LayUITableVO<List<PromotionSpecialOfferParticulars>> vo = promotionSpecialOfferParticularsService.findPageById(id);

        PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.put(id,vo);

        return vo;
    }

    //修改map缓存中的数据，并重新计算价格总和
    @PostMapping("/editMap")
    @ResponseBody
    public ResultVO editMap (PromotionSpecialOfferParticulars promotionSpecialOfferParticulars){

        LayUITableVO<List<PromotionSpecialOfferParticulars>> listLayUITableVO = PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.get(promotionSpecialOfferParticulars.getId());

        List<PromotionSpecialOfferParticulars> dataList = listLayUITableVO.getData();

        for (PromotionSpecialOfferParticulars data : dataList) {
            int recordId = promotionSpecialOfferParticulars.getRecordId();
            int recordId1 = data.getRecordId();
            if (recordId == recordId1){
                data.setSpecialPriceString(promotionSpecialOfferParticulars.getSpecialPriceString());
                data.setDiscountString(promotionSpecialOfferParticulars.getDiscountString());
            }
        }


        return ResultVOUtil.ok();
    }

    //刷新订单详情信息，将修改好的新的价格总和给页面
    @GetMapping("/refresh")
    @ResponseBody
    public LayUITableVO<List<PromotionSpecialOfferParticulars>> refresh (@RequestParam(defaultValue = "1") Integer page,
                                                                  @RequestParam(defaultValue = "10") Integer limit,
                                                                  String id){


        return PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.get(id);
    }


    //删除map缓存中的指定的一条详情信息
    @PostMapping("/delMap")
    @ResponseBody
    public ResultVO delMap (String id,String recordId){

        LayUITableVO<List<PromotionSpecialOfferParticulars>> listLayUITableVO = PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.get(id);

        List<PromotionSpecialOfferParticulars> dataList = listLayUITableVO.getData();

        for (PromotionSpecialOfferParticulars data : dataList) {
            int recordId1 = data.getRecordId();
            int recordId2 = Integer.valueOf(recordId);
            if (recordId1==recordId2){

                dataList.remove(data);
                break;
            }
        }
        promotionSpecialOfferParticularsService.deleteByIdAndRecordId(id,recordId);

        return ResultVOUtil.ok();
    }

    //选择菜品原料页面
    @GetMapping("/edit-chooseRecord-ui")
    public String editChooseMaterialUI(String merchantsId,String orderId,Model model){


        List<FoodCategory> foodCategoryList = foodCategoryService.selectBymerchantsId(merchantsId);
        model.addAttribute("foodCategoryList",foodCategoryList);
        model.addAttribute("merchantsId",merchantsId);
        model.addAttribute("orderId",orderId);

        return "promotion/specialOffer/chooseRecord";

    }

    //将选中的菜品原料信息放入到map缓存中
    @PostMapping("/addMap")
    @ResponseBody
    public ResultVO addMap ( @RequestBody Map<String,Object> map){


        List<Map<String,String>> listMap = (List<Map<String,String>>) map.get("data");
        String orderId = (String) map.get("orderId");

        LayUITableVO<List<PromotionSpecialOfferParticulars>> listLayUITableVO = PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.get(orderId);

        List<PromotionSpecialOfferParticulars> dataList = listLayUITableVO.getData();

        List<String > recordList = new ArrayList<>();
        for (PromotionSpecialOfferParticulars promotionSpecialOfferParticulars : dataList) {
            recordList.add(String.valueOf(promotionSpecialOfferParticulars.getRecordId()));
        }


        for (Map<String, String> stringStringMap : listMap) {
            PromotionSpecialOfferParticulars promotionSpecialOfferParticulars = new PromotionSpecialOfferParticulars();
            try {
                BeanUtils.populate(promotionSpecialOfferParticulars,stringStringMap);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
            if (recordList.size() !=0 && recordList.contains(promotionSpecialOfferParticulars.getId()))
                continue;
            promotionSpecialOfferParticulars.setRecordName(stringStringMap.get("foodName"));
           promotionSpecialOfferParticulars.setRecordId(Integer.valueOf(promotionSpecialOfferParticulars.getId()));
           promotionSpecialOfferParticulars.setId(orderId);
           promotionSpecialOfferParticulars.setSpecialPrice(null);
           dataList.add(promotionSpecialOfferParticulars);
        }



        return ResultVOUtil.ok();
    }


    //取消操作，删除map中的缓存
    @PostMapping("/delAllMap")
    @ResponseBody
    public ResultVO delAllMap (String id){


        Set<String> keySet = PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.keySet();
        for (String s : keySet) {
            if (s.equals(id)){
                PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.remove(id);
            }
        }


        return ResultVOUtil.ok();
    }

    //提交操作（修改或添加），判断订单详情的数据完整性，分别存入两表中，移除map缓存
    @PostMapping("/saveMap")
    @ResponseBody
    public ResultVO saveMap (PromotionSpecialOffer promotionSpecialOffer){

        LayUITableVO<List<PromotionSpecialOfferParticulars>> listLayUITableVO = PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.get(promotionSpecialOffer.getId());

        List<PromotionSpecialOfferParticulars> dataList = listLayUITableVO.getData();
        if (dataList.size()==0){
            throw new ManagermentSystemException(ManagermentSystemEnum.PARM_INCOMPLETE);
        }

        if (promotionSpecialOffer.getCategoryId() == 7001){
            for (PromotionSpecialOfferParticulars data : dataList) {
                if ("".equals(data.getSpecialPriceString()) || data.getSpecialPriceString() == null){
                    throw new ManagermentSystemException(ManagermentSystemEnum.PARM_INCOMPLETE);
                }
            }
        }else if (promotionSpecialOffer.getCategoryId() == 7002){
            for (PromotionSpecialOfferParticulars data : dataList) {
                if ("".equals(data.getDiscountString()) || data.getDiscountString() == null){
                    throw new ManagermentSystemException(ManagermentSystemEnum.PARM_INCOMPLETE);
                }
            }
        }

      promotionSpecialOfferService.update(promotionSpecialOffer);

        promotionSpecialOfferParticularsService.save(dataList);


        Set<String> keySet = PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.keySet();
        for (String s : keySet) {
            if (s.equals(promotionSpecialOffer.getId())){
                PROMOTION_SPECIAL_OFFER_PARTICULARS_MAP.remove(promotionSpecialOffer.getId());
            }
        }


        return ResultVOUtil.ok();
    }


    //跳转到添加页面
    @GetMapping("/add-ui")
    public String addUI(String merchantsId,Model model){

        PromotionSpecialOffer promotionSpecialOffer = new PromotionSpecialOffer();

        promotionSpecialOffer.setId("SD"+ GenerateOrdersIDUtil.generateOrdersID(1001));
        promotionSpecialOffer.setMerchantsId(Integer.valueOf(merchantsId));
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        String time =  df.format(new Date());// new Date()为获取当前系统时间
        promotionSpecialOffer.setPreparedBy("小红");
        promotionSpecialOffer.setPreparedDate(time);

        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();


        List<MemberCategory> memberCategoryList = memberCategoryService.selectAll();

        List<PromotionCategory> promotionCategoryList = promotionCategoryService.selectAll();

        model.addAttribute("merchantsInformationList",merchantsInformationList);

        model.addAttribute("promotionSpecialOffer",promotionSpecialOffer);
        model.addAttribute("memberCategoryList",memberCategoryList);
        model.addAttribute("promotionCategoryList",promotionCategoryList);


        return "promotion/specialOffer/add";

    }


    //跳转到修改页面
    @GetMapping("/show-ui")
    public String showUI(String id, Model model){

        PromotionSpecialOffer promotionSpecialOffer = promotionSpecialOfferService.selectById(id);
        List<MerchantsInformation> merchantsInformationList = merchantsInformationService.findAllIdAndName();
        List<MemberCategory> memberCategoryList = memberCategoryService.selectAll();

        List<PromotionCategory> promotionCategoryList = promotionCategoryService.selectAll();

        model.addAttribute("merchantsInformationList",merchantsInformationList);
        model.addAttribute("promotionSpecialOffer",promotionSpecialOffer);
        model.addAttribute("memberCategoryList",memberCategoryList);
        model.addAttribute("promotionCategoryList",promotionCategoryList);

        return "promotion/specialOffer/show";

    }


    //删除
    @PostMapping("/del")
    @ResponseBody
    public ResultVO del (String id){

        promotionSpecialOfferService.deleteById(id);

        promotionSpecialOfferParticularsService.deleteById(id);


        return ResultVOUtil.ok();
    }

}
